﻿// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Linq;
using System.Text;
using Utf8Json;

namespace SnapObjects.Data
{
    internal class UTF8ValueReader : IValueReader
    {
        private readonly IValueReader _valueReader;

        public UTF8ValueReader(string name, object value, JsonToken jsonToken)
        {
            if (jsonToken == JsonToken.Number && value is byte[] byts)
            {
                value = Encoding.UTF8.GetString(byts);

                _valueReader = new JValueReader(name, value);

                this.Value = _valueReader.ToDouble();
            }
            else
            {
                _valueReader = new JValueReader(name, value);

                this.Value = _valueReader.Value;
            }
        }

        public string Name => _valueReader.Name;

        public object Value { get; }

        public bool? ToBoolean()
        {
            return ValueConvert.Convert<bool?>(this.Value);
        }

        public DateTime? ToDateTime()
        {
            return _valueReader.ToDateTime();
        }

        public decimal? ToDecimal()
        {
            return _valueReader.ToDecimal();
        }

        public double? ToDouble()
        {
            return _valueReader.ToDouble();
        }

        public int? ToInt32()
        {
            return _valueReader.ToInt32();
        }

        public override string ToString()
        {
            return _valueReader.ToString();
        }
    }
}
